import {
  Button,
  Col,
  Form,
  Input,
  message,
  Radio,
  Row,
  Tabs,
  Tree,
  TreeSelect,
  Collapse,
  Select,
} from 'antd';
import React, { useEffect, useMemo, useState } from 'react';

import { history } from 'umi';

import { formatTreeData } from '@/services/common';
import {
  getByScope,
  sysResGetSubsystem,
  ucOrganizationGetId,
  ucOrganizationSave,
  ucOrganizationUpdate,
  commonMenuGetByScope,
} from '@/services/deptControl';
import { getStatusMap } from '@/services/common';

import styles from './index.less';
import { createFindByIDsFunc, formatLimitTree } from '../help';
import BackBtn from '@/components/BackBtn';

const { TabPane } = Tabs;
const { Panel } = Collapse;

// 表单初始值
const initialValues: any = {
  type: 2,
};

export default (props: any) => {
  const {
    location: { state },
  } = props;

  const user = JSON.parse(localStorage.getItem('user') as string) || {};
  // 用户权限
  // 1: admin，2：普通管理员，3:普通用户
  const userType = user?.type;

  const [form] = Form.useForm();
  // 编辑机构获取全部数据
  const [department, setDepartment] = useState({});
  // 子系统数据流
  const [subsystem, setSubsystem] = useState<any[]>([]);
  // 子系统菜单选择
  const [subsystemKey, setSubsystemKey] = useState('');
  // 子系统树形菜单选择数据流
  const [subsystemTreeData, setSubsystemTreeData] = useState<any>({});

  //行业
  const [industrySelect, setindustrySelect] = useState([]);
  //业务类别
  // const [businessSelect, setbusinessSelect] = useState([]);
  // 组织架构
  const [departmentTree, setDepartmentTree] = useState([]);

  // 页面类型
  const pageType = state?.pageType;
  // 是否可编辑
  const view = pageType === 'check';
  // 节点id
  const id = state?.id;
  // 节点类型
  const parentId = state?.parentId;
  // 是否为1级部门
  // 点击新增页面，当前节点为根节点时可功能鉴权
  // 点击编辑/详情页面，当前节点为一级节点可功能鉴权
  const isFirst =
    (pageType === 'add' && !parentId) ||
    ((pageType === 'edit' || pageType === 'check') && state?.isFirst === 1);
  // 是否展示父级节点选择框
  // 新增根节点不展示
  // 根节点的编辑和详情页面不展示
  const isShowParent =
    pageType === 'addNode' ||
    ((pageType === 'edit' || pageType === 'check') && !parentId);

  useEffect(() => {
    initFormData();
  }, [state]);

  useEffect(() => {
    getDepartmentTreeByRole();
    getStatus();
  }, []);

  // 根据机构id获取对应的资源信息
  const defaultMenuByDept = async (id?: any) => {
    const res = await commonMenuGetByScope({
      contain: 2,
      idList: [id],
      idType: 2,
      scope: 1,
    });

    if (res?.code === 200) {
      setSubsystem(formatTreeData(res?.data) || []);

      choiceTab(res?.data[0]?.id);
      setSubsystemKey(res?.data[0]?.id);
    }

    const idArr: any = {};
    (res?.data || []).forEach((item: any) => {
      idArr[item.id] = [];
      deptRecursion(idArr[item.id], item?.children);
    });
    setSubsystemTreeData(idArr);
  };

  // 根据机构树获取选中资源id
  const deptRecursion = (idArr: any[], menuArr: any[]) => {
    (menuArr || []).forEach((item: any) => {
      item?.flag && idArr.push(item.id);
      item?.children?.length > 0 && deptRecursion(idArr, item?.children);
    });
  };

  // 初始化请求数据
  const initFormData = () => {
    if (id) {
      ucOrganizationGetId(id).then((result) => {
        setDepartment(result?.data);
        defaultMenuByDept(result?.data?.id);
        // 新增页面只填充节点类型和父级节点
        if (pageType === 'add') {
          // 新增页面的父级节点展示点击的节点本身
          form.setFieldsValue({
            ...initialValues,
            parentId: result?.data.id,
          });
        } else {
          // 编辑和详情页面父级节点展示上一层节点
          form.setFieldsValue(result?.data);
        }
      });
    }
  };

  // 初始化组织树
  const getDepartmentTreeByRole = async () => {
    const orgType = userType === 1 ? 0 : 1;
    // 根据接口获取值
    let res = await getByScope({ orgType });

    // 写入值
    setDepartmentTree(formatTreeData(res?.data));
  };

  const getStatus = async () => {
    //行业
    const industryMap = await getStatusMap('uc_org_industry_type');
    //类别
    const businessMap = await getStatusMap('uc_org_business_type');
    setindustrySelect(industryMap.data);
  };

  // 保存（编辑&新增）
  const save = () => {
    form
      .validateFields()
      .then(async (value) => {
        // 获取checkedKeys下所有屏蔽的节点的id
        const checkedChildKeys = createFindByIDsFunc()(subsystem, checkedKeys);
        // 选择了的跟节点id
        const checkedNodeKeys = [];
        for (const key in subsystemTreeData) {
          const len = subsystemTreeData[key].length;
          if (len > 0) {
            checkedNodeKeys.push(Number(key));
          }
        }
        const allCheckedKeys = [...checkedChildKeys, ...checkedNodeKeys];
        if (pageType === 'edit') {
          const result = await ucOrganizationUpdate({
            ...department,
            ...value,
            sysFeatureResourceIds: allCheckedKeys,
          });
          if (result.code === 200) {
            message.success('数据编辑成功');
            history.push('/features/dept/index');
          }
        } else {
          const result = await ucOrganizationSave({
            ...value,
            sysFeatureResourceIds: allCheckedKeys,
          });
          if (result.code === 200) {
            message.success('数据新增成功');
            history.push('/features/dept/index');
          }
        }
      })
      .catch((errorInfo) => {
        console.log(errorInfo);
      });
  };

  // 合并树数组
  const checkedKeys = useMemo(() => {
    let arr: any[] = [];
    Object.values(subsystemTreeData).map((item: any) => {
      arr = [...arr, ...item];
    });
    return arr;
  }, [subsystemTreeData]);

  // 树勾选回调
  const treeCheck = (keys: any) => {
    const arr = { ...subsystemTreeData };
    arr[subsystemKey] = keys;
    setSubsystemTreeData(arr);
  };

  // 资源树
  const TreeSelectComponent = (subItem: any) => {
    const treeData = formatLimitTree(subItem?.children);
    return (
      <Collapse expandIconPosition="right">
        <Panel header={subItem?.name} key={subItem?.id}>
          <Tree
            onCheck={treeCheck}
            disabled={view}
            checkedKeys={(subsystemTreeData || {})[subsystemKey] || []}
            checkable
            treeData={treeData}
          />
        </Panel>
      </Collapse>
    );
  };

  // 资源子系统切换
  const choiceTab = async (key: any) => {
    setSubsystemKey(key);
  };

  return (
    <>
      <div className={styles.containerStyles}>
        <p className="page-title">基本信息</p>
        <Form layout="vertical" form={form} initialValues={initialValues}>
          <Row gutter={24}>
            <Col xs={24} sm={12}>
              <Form.Item
                label="节点类型"
                name="type"
                rules={[{ required: true }]}
              >
                <Radio.Group disabled={view}>
                  <Radio value={2}>部门</Radio>
                  <Radio value={1}>公司</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
            {
              // 编辑或详情展示
              (pageType === 'edit' || pageType === 'check') && (
                <Col xs={24} sm={12}>
                  <Form.Item label="机构编码" name="serialNo">
                    <Input disabled />
                  </Form.Item>
                </Col>
              )
            }
            {!isShowParent && (
              <Col xs={24} sm={12}>
                <Form.Item
                  label="父级节点"
                  name="parentId"
                  rules={[{ required: true }]}
                >
                  <TreeSelect disabled={true} treeData={departmentTree} />
                </Form.Item>
              </Col>
            )}
            <Col xs={24} sm={12}>
              <Form.Item
                label="机构名称"
                name="name"
                rules={[{ required: true }]}
              >
                <Input disabled={view} />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item label="机构英文名称" name="nameEn">
                <Input disabled={view} />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item label="简称" name="shortName">
                <Input disabled={view} />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item label="负责人姓名" name="personInCharge">
                <Input disabled={view} />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item label="联系方式" name="phone">
                <Input disabled={view} />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item label="行业" name="industryType">
                <Select disabled={view}>
                  {industrySelect.map((item: any) => (
                    <Select.Option key={item.dictValue} value={+item.dictValue}>
                      {item.dictLabel}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item label="地址" name="address">
                <Input disabled={view} />
              </Form.Item>
            </Col>
            {/* <Col xs={24} sm={12}>
              <Form.Item label="业务类别" name="businessType">
                <Select disabled={view}>
                  {businessSelect.length > 0 &&
                    businessSelect.map((item: any) => (
                      <Select.Option
                        key={item.dictValue}
                        value={+item.dictValue}
                      >
                        {item.dictLabel}
                      </Select.Option>
                    ))}
                </Select>
              </Form.Item>
            </Col> */}
            <Col xs={24} sm={12}>
              <Form.Item label="简介" name="introduction">
                <Input disabled={view} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
        {isFirst && (
          <>
            <p className="page-title">功能权限</p>
            <Tabs defaultActiveKey={subsystem[0]?.id} onTabClick={choiceTab}>
              {subsystem.map((item: any) => (
                <TabPane tab={item?.name} key={item?.id}>
                  {TreeSelectComponent(item)}
                </TabPane>
              ))}
            </Tabs>
          </>
        )}
      </div>
      <div className={styles.operatingContainer}>
        <BackBtn />
        {pageType !== 'check' && (
          <div>
            <Button
              onClick={() => {
                form.resetFields();
                history.push('/features/dept/index');
              }}
            >
              取消
            </Button>
            <Button type="primary" onClick={save}>
              保存
            </Button>
          </div>
        )}
      </div>
    </>
  );
};
